﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Li.DingTalk;
using Newtonsoft.Json;

namespace DingTalkAgent.Web.Areas.mobile.Controllers
{
    public class loginController : Controller
    {
        // GET: mobile/login
        public ActionResult Index(string  backurl = "/mobile/home/index", string CorpID = "")
        {
            try
            {
                //如果CorpID为空表示，是应用中停留过长的超时，直接关闭页面返回工作台重进入.
                var url = Discuz.Common.DNTRequest.GetUrl();
                //if (url.Contains("?"))
                //{
                //    url = url.Split('?')[0];
                //}
                ViewBag.url = Server.UrlPathEncode(url);
                ViewBag.bakurl = backurl;

                //玉溪水利，测试模块
                var agentid = "167273568";
                if (url.ToLower().Contains("patrollog"))
                {
                    agentid = "167257984";
                }
                if (url.ToLower().Contains("riversource"))
                {
                    agentid = "167273568";
                }

                //查实的玉溪水利


                ViewBag.agentid = agentid;
                return View();
            }
            catch(Exception ex)
            {
                return Content(ex.Message);
            }
        }
        /// <summary>
        /// 返回钉钉的配置对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="CorpID">不同企业的</param>
        /// <returns></returns>
        public ActionResult init(string url,string CorpID,string agentid="")
        {
            try
            {
               
                if(string.IsNullOrEmpty(agentid))
                {
                    agentid = "167273568";
                }

                CorpID = ConfigHelper.FetchCorpID();
                //检查是否注册
                if (!Li.DingTalk.AccessTokenContainer.CheckRegistered(CorpID))
                {
                    //查询CorpSecret
                    var CorpSecret = ConfigHelper.FetchCorpSecret();
                    Li.DingTalk.AccessTokenContainer.Register(CorpID, CorpSecret);
                }
                //获取 AccessToken
                string AccessToken = Li.DingTalk.AccessTokenContainer.TryGetToken(CorpID);
                //获取js_ticket
                string ticket = Li.DingTalk.AccessTokenContainer.TryGetJsTicket(CorpID, AccessToken);
                var m = new Li.DingTalk.Model.ddConfig()
                {
                    corpId = CorpID,
                    url = Server.UrlDecode(url),
                    agentId = Convert.ToInt32(agentid),
                    nonceStr = Li.DingTalk.Helper.JSSDKHelper.GetNoncestr(),
                    timeStamp = Discuz.Common.Utils.ConvertToUnixTimestamp(DateTime.Now).ToString()
                };
                m.signature = Li.DingTalk.Helper.JSSDKHelper.GetSignature(ticket, m.nonceStr, m.timeStamp, url).ToLower();
                return Json(m);

            }
            catch(Exception ex)
            {
                //写入错误日志

               Discuz.Common.LogInfo.WriteLog(Server.MapPath("\\Error\\Error.txt"), "免登录签名认证", ex.Message.ToString() + "\r\n\r\n path:" + Discuz.Common.DNTRequest.GetRawUrl().ToString());
                return Content(ex.ToString());
            }
        }


        /// <summary>
        /// 免登录。获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="CorpID"></param>
        /// <returns></returns>
        public ActionResult userinfo(string code, string CorpID) 
        {
            try
            {
                 Discuz.Common.LogInfo.WriteLog(Server.MapPath("\\Error\\Error.txt"), "userinfo-code:", code);

                CorpID = ConfigHelper.FetchCorpID();
                //检查是否注册
                if (!Li.DingTalk.AccessTokenContainer.CheckRegistered(CorpID))
                {
                    //查询CorpSecret
                    var CorpSecret = ConfigHelper.FetchCorpSecret();
                    Li.DingTalk.AccessTokenContainer.Register(CorpID, CorpSecret);
                }
                //获取 AccessToken
                string AccessToken = Li.DingTalk.AccessTokenContainer.TryGetToken(CorpID);
                var user=Li.DingTalk.Model.Contacts.userHD.geuser(AccessToken, code);

                SqlData.users dh = new SqlData.users();
                var m = dh.login(user.userid);
                if(m==null)
                {
                    return Content("当前用户不在河长制信息管理平台中.");
                }
                else {
                    Session["mobile"] = m;
                    return Content("true");
                }
            }
            catch (Exception ex)
            {
                //写入错误日志

                Discuz.Common.LogInfo.WriteLog(Server.MapPath("\\Error\\Error.txt"), "免登录签名认证", ex.Message.ToString() + "\r\n\r\n path:" + Discuz.Common.DNTRequest.GetRawUrl().ToString());
                return Content("");
            }
        }
    }
}